/*
 * @Date: 2023-01-11 13:53:54
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-24 17:12:24
 * @FilePath: \A19\backend\src\flowNodes\isGet.ts
 */
import { BaseServer, HttpConnection } from "tsrpc";
import { ServiceType } from "../shared/protocols/serviceProto";
import fs from 'fs'
import path from "path";
import { Stream } from 'stream';
import { mimeMap } from "../utils/mimeMap";
import { splitParams } from "../utils/splitParams";

export default async function (server: BaseServer<ServiceType>) {
    // Custom HTTP Reponse
    server.flows.preRecvDataFlow.push(async v => {
        let conn = v.conn as HttpConnection;

        if (conn.httpReq.method === 'GET') {
            // 静态文件服务
            if (conn.httpReq.url) {
                // 检测文件是否存在
                const url = conn.httpReq.url.split('?')[0]
                const download = splitParams(conn.httpReq.url)['download'] === 'true'
                let resFilePath = path.join('uploads', url)
                // console.log((resFilePath));
                let isExisted = await fs.promises.access((resFilePath)).then(() => true).catch(() => false);
                // console.log(isExisted);
                if (isExisted) {
                    // console.log(url + 'found');
                    if(url === '/'){
                        conn.httpRes.end('Not Found');
                        return undefined;
                    }
                    if(conn.httpReq.headers['sec-fetch-dest'] === 'video' || conn.httpReq.headers['sec-fetch-dest'] === 'audio' && download === false){
                        // const stream = fs2.createReadStream(resFilePath)
                        // stream.pipe(conn.httpRes)
                        // return undefined
                        const index = url.indexOf('.')
                        const type = (url.slice(index + 1)).toLocaleLowerCase()
                        console.log(type);
                        const contentType = mimeMap[type]
                        console.log(contentType);

                        const res = conn.httpRes
                        const req = conn.httpReq
                        fs.stat(resFilePath,(err,stats) =>{
                           if(err){
                            res.end(err)
                            return undefined;
                           }

                           const range = req.headers.range
                           if(!range) {
                            res.end('Not Found')
                            return undefined;
                           }

                        //    const positions = range.replace(/bytes=/,"").split('-')
                           const positions = range.match(/=(\d+)-(\d+)?/) as RegExpMatchArray
                           const start = parseInt(positions[1],10)
                           const total =stats.size
                           let end = positions[2]? parseInt(positions[2],10) : start + 1024 * 1024
                           if(end > stats.size - 1) end = stats.size - 1

                           const chunksize = end - start + 1

                           res.writeHead(206,{
                            'Content-Range' : 'bytes ' + start + '-' + end + '/' + total,
                            'Accept-Ranges' : 'bytes',
                            'Content-Length' : chunksize,
                            'Content-Type' : contentType
                           })

                           const stream = fs.createReadStream(resFilePath,{
                            start,
                            end
                           })
                           .on('open',() =>{
                            stream.pipe(res)
                           })
                           .on('error',(err) => {
                            res.end(err)
                           })
                        })
                    }
                    // 返回文件内容
                    let content = await fs.promises.readFile(resFilePath);
                    conn.httpRes.end(content);
                    return undefined;
                }
            }
            // 默认 GET 响应
            conn.httpRes.end('Not Found');
            return undefined;
        }

        return v;
    })
}